{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 生成器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`while` 循环通常有这样的形式：\n",
    "\n",
    "```python\n",
    "<do setup>\n",
    "result = []\n",
    "while True:\n",
    "    <generate value>\n",
    "    result.append(value)\n",
    "    if <done>:\n",
    "        break\n",
    "```\n",
    "\n",
    "使用迭代器实现这样的循环：\n",
    "\n",
    "```python\n",
    "class GenericIterator(object):\n",
    "    def __init__(self, ...):\n",
    "        <do setup>\n",
    "        # 需要额外储存状态\n",
    "        <store state>\n",
    "    def next(self): \n",
    "        <load state>\n",
    "        <generate value>\n",
    "        if <done>:\n",
    "            raise StopIteration()\n",
    "        <store state>\n",
    "        return value\n",
    "```\n",
    "\n",
    "更简单的，可以使用生成器：\n",
    "\n",
    "```python\n",
    "def generator(...):\n",
    "    <do setup>\n",
    "    while True:\n",
    "        <generate value>\n",
    "        # yield 说明这个函数可以返回多个值！\n",
    "        yield value\n",
    "        if <done>:\n",
    "            break\n",
    "```\n",
    "\n",
    "生成器使用 `yield` 关键字将值输出，而迭代器则通过 `next` 的 `return` 将值返回；与迭代器不同的是，生成器会自动记录当前的状态，而迭代器则需要进行额外的操作来记录当前的状态。\n",
    "\n",
    "对于之前的 `collatz` 猜想，简单循环的实现如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1\n"
     ]
    }
   ],
   "source": [
    "def collatz(n):\n",
    "    sequence = []\n",
    "    while n != 1:\n",
    "        if n % 2 == 0:\n",
    "            n /= 2\n",
    "        else:\n",
    "            n = 3*n + 1\n",
    "        sequence.append(n)\n",
    "    return sequence\n",
    "\n",
    "for x in collatz(7):\n",
    "    print x,"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "迭代器的版本如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1\n"
     ]
    }
   ],
   "source": [
    "class Collatz(object):\n",
    "    def __init__(self, start):\n",
    "        self.value = start\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "    \n",
    "    def next(self):\n",
    "        if self.value == 1:\n",
    "            raise StopIteration()\n",
    "        elif self.value % 2 == 0:\n",
    "            self.value = self.value/2\n",
    "        else:\n",
    "            self.value = 3*self.value + 1\n",
    "        return self.value\n",
    "\n",
    "for x in Collatz(7):\n",
    "    print x,"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成器的版本如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1\n"
     ]
    }
   ],
   "source": [
    "def collatz(n):\n",
    "    while n != 1:\n",
    "        if n % 2 == 0:\n",
    "            n /= 2\n",
    "        else:\n",
    "            n = 3*n + 1\n",
    "        yield n\n",
    "\n",
    "for x in collatz(7):\n",
    "    print x,"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上，生成器也是一种迭代器："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<generator object collatz at 0x0000000003B63750>\n"
     ]
    }
   ],
   "source": [
    "x = collatz(7)\n",
    "print x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "它支持 `next` 方法，返回下一个 `yield` 的值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22\n",
      "11\n"
     ]
    }
   ],
   "source": [
    "print x.next()\n",
    "print x.next()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__iter__` 方法返回的是它本身："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<generator object collatz at 0x0000000003B63750>\n"
     ]
    }
   ],
   "source": [
    "print x.__iter__()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之前的二叉树迭代器可以改写为更简单的生成器模式来进行中序遍历："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class BinaryTree(object):\n",
    "    def __init__(self, value, left=None, right=None):\n",
    "        self.value = value\n",
    "        self.left = left\n",
    "        self.right = right\n",
    "\n",
    "    def __iter__(self):\n",
    "        # 将迭代器设为生成器方法\n",
    "        return self.inorder()\n",
    "    \n",
    "    def inorder(self):\n",
    "        # traverse the left branch\n",
    "        if self.left is not None:\n",
    "            for value in self.left:\n",
    "                yield value\n",
    "                \n",
    "        # yield node's value\n",
    "        yield self.value\n",
    "        \n",
    "        # traverse the right branch\n",
    "        if self.right is not None:\n",
    "            for value in self.right:\n",
    "                yield value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "非递归的实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def inorder(self):\n",
    "    node = self\n",
    "    stack = []\n",
    "    while len(stack) > 0 or node is not None:\n",
    "        while node is not None:\n",
    "            stack.append(node)\n",
    "            node = node.left\n",
    "        node = stack.pop()\n",
    "        yield node.value\n",
    "        node = node.right"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3 4 5 6 7 8\n"
     ]
    }
   ],
   "source": [
    "tree = BinaryTree(\n",
    "    left=BinaryTree(\n",
    "        left=BinaryTree(1),\n",
    "        value=2,\n",
    "        right=BinaryTree(\n",
    "            left=BinaryTree(3),\n",
    "            value=4,\n",
    "            right=BinaryTree(5)\n",
    "        ),\n",
    "    ),\n",
    "    value=6,\n",
    "    right=BinaryTree(\n",
    "        value=7,\n",
    "        right=BinaryTree(8)\n",
    "    )\n",
    ")\n",
    "for value in tree:\n",
    "    print value,"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
